var ClubRankingTab = Item.extend({
    _ccsFileName: res.ClubRankingTab_json,
    _clubId: null,
    _tableViewList: [],

    _rankTimeType: [
        'today',     //今日榜
        'yesterday', //昨日榜单
        'week',      //本周榜
    ],
    //筛选类型
    _orderTypeArr: [
        'winnerCount', //大赢家
        'totalScore',  //积分
        'roomCount'    //局数
    ],

    _selectedTimeType: '',
    _selectedMapIdStr: '',
    _selectedOrderType: '',

    _selectStartData: null,   //选择的查询起始时间
    _selectEndData: null,    //选择的查询结束时间
    initItem: function (clubId) {
        this._clubId = clubId;
        var today = new Date();

        this._selectedTimeType = this._rankTimeType[0];
        this._selectedOrderType = this._orderTypeArr[0];
        this._selectedMapIdStr = ClubDataManager.getAllAppWanfaMapIdStr();

        this._initTableView();
        this._initDropDownMenu1();
        this._initDropDownMenu2();
        this._initDropDownMenu3();

        var year = today.getFullYear();
        var month = today.getMonth() + 1;
        var day = today.getDate();
        var arr = ClubDataManager.dateFromat(year, month, day);
        this._nodeList['dateEndNode.dateLabel'].setString(arr[0] + '/' + arr[1] + '/' + arr[2]);
        this._nodeList['dateStartNode.dateLabel'].setString(arr[0] + '/' + arr[1] + '/' + arr[2]);

        this._nodeList['btn_memberView'].isView = 'close';
        this._nodeList['btn_memberHide'].isView = 'open';
    },

    _initClickListeners: function () {
        this._clickListeners = {
            'btn_memberView': '_clickMemberViewOrHide',
            'btn_memberHide': '_clickMemberViewOrHide',
            'dateStartNode': '_clickDate',
            'dateEndNode': '_clickDate',
        };
    },

    /**
     * 监听亲友圈消息
     * @private
     */
    _initEventListeners: function () {
        this._eventListeners = {};
        //监听 消息 事件
        this._eventListeners[ClubRecordCode.RankingsList] = '_clubRankingsHandler';
    },

    /**
     * 初始化TableView
     */
    _initTableView: function () {
        var nodeContent = this._nodeList['nodeContent'];
        var tableViewSize = nodeContent.getContentSize();
        this._tableView = new cc.TableView(this, cc.size(tableViewSize.width, tableViewSize.height));
        this._tableView.setDelegate(this);
        this._tableView.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
        this._tableView.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN);
        this._tableView.setPosition(nodeContent.getPosition());
        nodeContent.getParent().addChild(this._tableView);
    },
    /**
     * 初始化下拉菜单
     * @private
     */
    _initDropDownMenu1: function () {
        var config = {
            selectBgRes: res.dropDownMenuTopBack,
            selectBtnRes: res.dropDownMenuBtn,
            menuRes: res.dropDownMenuBack2,
            normalIndex: 0,
            fontSize: 20,
            dataArr: ['今日榜', '昨日榜', '本周榜'],
            selectCallBack: this._dropDownMenuHandler1.bind(this)
        };
        this._dropDownMenu = new DropDownMenu(config);
        this._nodeList['menu1'].getParent().addChild(this._dropDownMenu);
        this._dropDownMenu.setPosition(this._nodeList['menu1'].getPosition());
    },

    _clubRankingsHandler: function (data) {
        if (!ClubDataManager.isSelfAdministration(this._clubId, gameData.uid) && !this._checkRankTimeTypeIsOpen(this._selectedTimeType)) {
            data = [];
        }
        this._tableViewList = data;
        this._tableView.reloadData();

        this._refreshMyRankInfo(data);
    },


    /**
     * 初始化下拉菜单
     * @private
     */
    _initDropDownMenu2: function () {
        var config = {
            selectBgRes: res.dropDownMenuTopBack,
            selectBtnRes: res.dropDownMenuBtn,
            menuRes: res.dropDownMenuBack2,
            normalIndex: 0, fontSize: 20,
            dataArr: _.keys(club.ClubWanfaFilter),
            selectCallBack: this._dropDownMenuHandler2.bind(this)
        };
        this._dropDownMenu = new DropDownMenu(config);
        this._nodeList['menu2'].getParent().addChild(this._dropDownMenu);
        this._dropDownMenu.setPosition(this._nodeList['menu2'].getPosition());
    },

    /**
     * 初始化下拉菜单
     * @private
     */
    _initDropDownMenu3: function () {
        var config = {
            selectBgRes: res.dropDownMenuTopBack,
            menuRes: res.dropDownMenuBack2,
            selectBtnRes: res.dropDownMenuBtn,
            normalIndex: 0, fontSize: 20,
            dataArr: ['大赢家', '积分', '局数'],
            selectCallBack: this._dropDownMenuHandler3.bind(this)
        };
        this._dropDownMenu = new DropDownMenu(config);
        this._nodeList['menu3'].getParent().addChild(this._dropDownMenu);
        this._dropDownMenu.setPosition(this._nodeList['menu3'].getPosition());
    },

    _dropDownMenuHandler1: function (content, index) {
        this._selectStartData = null;
        this._selectEndData = null;
        this._selectedTimeType = this._rankTimeType[index];
        this._refreshRankingSeePower();
        this._changeFilter();
    },

    _dropDownMenuHandler2: function (content) {
        if (content == '所有玩法') {
            this._selectedMapIdStr = ClubDataManager.getAllAppWanfaMapIdStr();
        } else {
            this._selectedMapIdStr = club.ClubWanfaFilter[content].join(',');
        }
        this._changeFilter();
    },

    _dropDownMenuHandler3: function (content, index) {
        this._selectedOrderType = this._orderTypeArr[index];
        this._changeFilter();

        var arrName = ['次数', '积分', '局数'];
        this._nodeList['NumberLabel'].setString(arrName[index]);
    },

    /**
     * 点击成员是否可见
     * @private
     */
    _clickMemberViewOrHide: function (target) {
        var view = target.isView;
        this._nodeList['btn_memberView'].setVisible(view != 'close');
        this._nodeList['btn_memberHide'].setVisible(view != 'open');
        network.send(2103, {
            cmd: ClubMsgCode.ClubParamSet,
            key: 'rankList' + this._selectedTimeType,
            value: view,
            club_id: this._clubId
        });
    },

    _clickDate: function (target) {
        var today = new Date();
        var curyear = today.getFullYear();
        var curmonth = today.getMonth() + 1;
        var curday = today.getDate();
        var handler = function (year, month, day) {
            var arr = ClubDataManager.dateFromat(year, month, day);
            if (target.getName() == 'dateEndNode') {
                this._nodeList['dateEndNode.dateLabel'].setString(arr[0] + '/' + arr[1] + '/' + arr[2]);
            } else {
                this._nodeList['dateStartNode.dateLabel'].setString(arr[0] + '/' + arr[1] + '/' + arr[2]);
            }
            this._selectedTimeType = null;
            this._selectStartData = this._nodeList['dateStartNode.dateLabel'].getString().replace(/\//g, '-');
            this._selectEndData = this._nodeList['dateEndNode.dateLabel'].getString().replace(/\//g, '-');
            this._changeFilter();
        };
        var _clubPowerDate = null;
        if (target.getName() == 'dateEndNode') {
            var startStr = this._nodeList['dateStartNode.dateLabel'].getString().split('/');
            _clubPowerDate = new ClubPowerDate(curyear, curmonth, curday, handler.bind(this), [startStr[0], startStr[1], startStr[2]], null, 1);
        } else {
            _clubPowerDate = new ClubPowerDate(curyear, curmonth, curday, handler.bind(this), null, null, 1);
        }
        _clubPowerDate.x = -400;
        _clubPowerDate.getChildByName('Node').getChildByName('modalLayer').setOpacity(0);
        this.addChild(_clubPowerDate);
    },

    /**
     * 刷新界面显示
     */
    refreshView: function () {
        this._changeFilter();
        this._refreshRankingSeePower();
    },

    _changeFilter: function () {
        clubMsgManager.requestRanking(this._clubId,
            this._selectedMapIdStr,
            this._selectedTimeType,
            this._selectStartData,
            this._selectEndData,
            this._selectedOrderType
        );
    },

    tableCellAtIndex: function (table, idx) {
        var cell = table.dequeueCell();
        var node = null;
        if (cell == null) {
            cell = new cc.TableViewCell();
            node = addItem('ClubRankingItem', cell, idx, this._tableViewList[idx], this._selectedOrderType);
            node.setName("itemCell");
        } else {
            node = cell.getChildByName("itemCell");
            node.setData(idx, this._tableViewList[idx], this._selectedOrderType);
        }
        return cell;
    },
    tableCellTouched: function (table, cell) {
    },
    tableCellSizeForIndex: function (table, idx) {
        return cc.size(1016, 64);
    },
    numberOfCellsInTableView: function (table) {
        return this._tableViewList.length;
    },

    /**
     * 检测排行榜类型是否开启查看权限
     * @param rankType
     * @returns {boolean}
     */
    _checkRankTimeTypeIsOpen: function (rankType) {
        if (rankType == null) return true;
        var clubData = ClubDataManager.getClubData(this._clubId);
        var params = clubData['param'];
        var isCanOpenRankList = false;
        if (params && params['rankList' + rankType]) {
            if (params['rankList' + rankType] == 'open') {
                isCanOpenRankList = true;
            } else {
                isCanOpenRankList = false;
            }
        }
        return isCanOpenRankList;
    },

    _refreshRankingSeePower: function () {
        var isOpen = this._checkRankTimeTypeIsOpen(this._selectedTimeType);
        this._nodeList['btn_memberView'].setVisible(isOpen);
        this._nodeList['btn_memberHide'].setVisible(!isOpen);
        this._checkIsViewMemberView();
    },

    /**
     * 检测是否显示成员可见按钮
     * @private
     */
    _checkIsViewMemberView: function () {
        var clubInfo = ClubDataManager.getClubData(this._clubId);
        if (clubInfo && gameData.uid != clubInfo['owner_uid']) {
            this._nodeList['btn_memberView'].setVisible(false);
            this._nodeList['btn_memberHide'].setVisible(false);
            this._nodeList['memberViewLabel'].setVisible(false);
        }
    },

    /**
     * 刷新自己的排行榜数据
     * @param data  所有的排行榜数据
     * @private
     */
    _refreshMyRankInfo: function (data) {
        var myRank = 0;
        var rankInfo = null;
        for (var i = 0; i < data.length; i++) {
            if (data[i]['playerId'] == gameData.uid) {
                myRank = i;
                rankInfo = data[i];
            }
        }
        var rankResArr = [
            res.club_icon_first,
            res.club_icon_second,
            res.club_icon_third
        ];
        if (rankInfo) {
            var isViewRankIcon = myRank <= 3;
            this._nodeList['icon_rank'].setVisible(isViewRankIcon);
            this._nodeList['myRankLabel'].setVisible(!isViewRankIcon);
            if (myRank < 3) {
                this._nodeList['icon_rank'].setTexture(rankResArr[myRank]);
            } else {
                this._nodeList['myRankLabel'].setString(myRank + 1);
            }
            this._nodeList['myNum'].setString(rankInfo[this._selectedOrderType]);
        } else {
            this._nodeList['myNum'].setString('---');
            this._nodeList['icon_rank'].setVisible(false);
            this._nodeList['myRankLabel'].setString('未上榜');
            this._nodeList['myRankLabel'].setVisible(true);
        }
        this._nodeList['myName'].setString(ellipsisStr(gameData.nickname, ClubDataManager.NirckNameSize));
        this._nodeList['myUid'].setString(gameData.uid);
        loadImageToSprite(gameData.headimgurl, this._nodeList['head'], true);
    }
});